package com.aiyige.page.my.merchandisemanagement.adapter;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ActionEngine;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.LearnVideoModelDao;
import com.aiyige.base.db.dao.MajorCourseDBModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.db.table.MajorCourseDBModel;
import com.aiyige.base.db.table.TraingClassDBModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.base.eventbus.EventDeleteSearchMoment;
import com.aiyige.base.eventbus.EventEditLearnVideoFinish;
import com.aiyige.base.eventbus.EventEditMajorCourseFinish;
import com.aiyige.base.eventbus.EventPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventSelectGuarantee;
import com.aiyige.base.eventbus.EventSelectTraingCard;
import com.aiyige.model.moment.backup.CardBackup;
import com.aiyige.model.moment.backup.DetailBackup;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.SingleVideo;
import com.aiyige.model.moment.entity.VideoCourse;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.my.merchandisemanagement.MMPage;
import com.aiyige.page.publish.CommonTipDialog;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoFormModel;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoItem;
import com.aiyige.page.publish.majorcourse.model.ClassLocation;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.page.publish.selectcoursetype.model.CourseTypeItem;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selectlearntarget.model.SelectLearnTargetItem;
import com.aiyige.page.publish.selectsuitablepeople.model.SelectSuitablePeopleItem;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.selectteacher.model.TeacherItem;
import com.aiyige.page.publish.selecttraingcard.model.TraingCard;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.ColorUtil;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.MomentUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.WebImageUrlModifier;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.RoundCornerImageView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.vondear.rxtools.RxTextTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

public class MMAdapter extends BaseQuickAdapter<MultiItemEntity, BaseViewHolder> {
    FragmentActivity mActivity;

    CommonBottomDialogFragment publishedLearnVideoDialog;
    CommonBottomDialogFragment notPublishedLearnVideoDialog;
    CommonBottomDialogFragment inReviewLearnVideoDialog;
    CommonBottomDialogFragment rejectLearnVideoDialog;
    CommonBottomDialogFragment uploadingLearnVideoDialog;

    CommonBottomDialogFragment publishedCourseDialog;
    CommonBottomDialogFragment notPublishedCourseDialog;
    CommonBottomDialogFragment inReviewCourseDialog;
    CommonBottomDialogFragment rejectCourseDialog;
    CommonBottomDialogFragment uploadingCourseDialog;
    CommonBottomDialogFragment serverTranscodingCourseDialog;

    CommonBottomDialogFragment publishedCourseNoEditCopyDialog;
    CommonBottomDialogFragment notPublishedCourseNoEditCopyDialog;
    CommonBottomDialogFragment inReviewCourseNoEditCopyDialog;
    CommonBottomDialogFragment rejectCourseNoEditCopyDialog;
    CommonBottomDialogFragment serverTranscodingCourseNoEditCopyDialog;


    EventBus eventBus;
    int currentPosition;
    TrackEvent trackEvent = new TrackEvent();
    Comparator<MultiItemEntity> comparator;
    boolean enableHighlight = false;

    public boolean isEnableHighlight() {
        return enableHighlight;
    }

    public void setEnableHighlight(boolean enableHighlight) {
        this.enableHighlight = enableHighlight;
    }

    public MMAdapter(FragmentActivity activity) {
        super(new LinkedList<MultiItemEntity>());
        this.mActivity = activity;
        eventBus = EventBus.builder().build();
        initCourseDialog();
        initLearnVideoDialog();
        comparator = new Comparator<MultiItemEntity>() {
            @Override
            public int compare(MultiItemEntity o1, MultiItemEntity o2) {
                long o1ReleaseDate = 0;
                long o2ReleaseDate = 0;
                switch (o1.getItemType()) {
                    case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                        o1ReleaseDate = ((LearnVideoModel) o1).getReleaseDate();
                        break;
                    case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                        o1ReleaseDate = ((MajorCourseDBModel) o1).getReleaseDate();
                        break;
                }
                switch (o2.getItemType()) {
                    case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                        o2ReleaseDate = ((LearnVideoModel) o2).getReleaseDate();
                        break;
                    case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                        o2ReleaseDate = ((MajorCourseDBModel) o2).getReleaseDate();
                        break;
                }
                long diff = o2ReleaseDate - o1ReleaseDate;
                if (diff > 0) {
                    return 1;
                } else if (diff < 0) {
                    return -1;
                } else {
                    return 0;
                }
            }
        };
    }

    private void initCourseDialog() {
        publishedCourseNoEditCopyDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_published_item_no_edit_copy_dialog)
                .viewIdList(R.id.deleteBtn, R.id.cancelBtn, R.id.cancelPublishedBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.cancelPublishedBtn:
                                new CancelPublishCourseAsyncTask().execute(position);
                                break;

                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.deleteBtn:
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();

        notPublishedCourseNoEditCopyDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_not_published_item_no_edit_copy_dialog)
                .viewIdList(R.id.cancelBtn, R.id.publishedBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.publishedBtn: {
                                new CourseSubmitReviewAsyncTask().execute(position);
                                break;
                            }

                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }


                            case R.id.deleteBtn:
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        inReviewCourseNoEditCopyDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_inreview_item_no_edit_copy_dialog)
                .viewIdList(R.id.cancelPublishedBtn, R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.cancelPublishedBtn: {
                                new CancelPublishCourseAsyncTask().execute(position);
                                break;
                            }

                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }

                            case R.id.deleteBtn: {
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                            }
                        }
                    }
                })
                .build();

        serverTranscodingCourseNoEditCopyDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_server_transcoding_item_no_edit_copy_dialog)
                .viewIdList(R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {

                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }

                            case R.id.deleteBtn: {
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                            }
                        }
                    }
                })
                .build();
        rejectCourseNoEditCopyDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_reject_item_no_edit_copy_dialog)
                .viewIdList(R.id.cancelBtn, R.id.rejectReasonBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.rejectReasonBtn:
                                try {
                                    String rejectReason = MomentUtil.extractRejectReason(((MajorCourseDBModel) getItem(position)).getRejectReason());
                                    CommonTipDialog.newInstance(rejectReason)
                                            .show(mActivity.getSupportFragmentManager(), "");
                                } catch (Exception e) {
                                }
                                break;
                            case R.id.deleteBtn:
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        publishedCourseDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_published_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.cancelPublishedBtn, R.id.editBtn, R.id.bindTraingCardBtn, R.id.copyBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.cancelPublishedBtn:
                                new CancelPublishCourseAsyncTask().execute(position);
                                break;
                            case R.id.editBtn:
                                currentPosition = position;
                                registerGlobalEventBus();
                                new EditCourseAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.copyBtn:
                                new CopyCourseAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.deleteBtn:
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();

        notPublishedCourseDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_not_published_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.publishedBtn, R.id.editBtn, R.id.bindTraingCardBtn, R.id.copyBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.publishedBtn: {
                                new CourseSubmitReviewAsyncTask().execute(position);
                                break;
                            }
                            case R.id.editBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                new EditCourseAsyncTask(mActivity).execute(position);
                                break;
                            }
                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.copyBtn:
                                new CopyCourseAsyncTask(mActivity).execute(position);
                                break;

                            case R.id.deleteBtn:
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        inReviewCourseDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_inreview_item_dialog)
                .viewIdList(R.id.cancelPublishedBtn, R.id.editBtn, R.id.bindTraingCardBtn, R.id.copyBtn, R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.cancelPublishedBtn: {
                                new CancelPublishCourseAsyncTask().execute(position);
                                break;
                            }
                            case R.id.editBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                new EditCourseAsyncTask(mActivity).execute(position);
                                break;
                            }
                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.copyBtn: {
                                new CopyCourseAsyncTask(mActivity).execute(position);
                                break;
                            }
                            case R.id.deleteBtn: {
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                            }
                        }
                    }
                })
                .build();

        serverTranscodingCourseDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_server_transcoding_item_dialog)
                .viewIdList(R.id.editBtn, R.id.bindTraingCardBtn, R.id.copyBtn, R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.editBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                new EditCourseAsyncTask(mActivity).execute(position);
                                break;
                            }
                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.copyBtn: {
                                new CopyCourseAsyncTask(mActivity).execute(position);
                                break;
                            }
                            case R.id.deleteBtn: {
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                            }
                        }
                    }
                })
                .build();
        rejectCourseDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_reject_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.editBtn, R.id.rejectReasonBtn, R.id.deleteBtn, R.id.copyBtn, R.id.bindTraingCardBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.editBtn:
                                currentPosition = position;
                                registerGlobalEventBus();
                                new EditCourseAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.bindTraingCardBtn: {
                                currentPosition = position;
                                registerGlobalEventBus();
                                String channel = "";
                                try {
                                    PublishInterestItem publishInterestItem = JSON.parseObject(((MajorCourseDBModel) getItem(position)).getInterest(), PublishInterestItem.class);
                                    channel = publishInterestItem.getParent().getId();
                                } catch (Exception e) {
                                }
                                List<TraingCard> traingCardList = new LinkedList<>();
                                try {
                                    traingCardList = JSON.parseArray(((MajorCourseDBModel) getItem(position)).getTraingCard(), TraingCard.class);
                                } catch (Exception e) {

                                }
                                ARouter.getInstance()
                                        .build(ARouterConfig.SelectTraingCardPage)
                                        .withString("channel", channel)
                                        .withBoolean("postEvent", true)
                                        .withObject("selectedCards", traingCardList)
                                        .navigation();
                                break;
                            }
                            case R.id.rejectReasonBtn:
                                try {
                                    String rejectReason = MomentUtil.extractRejectReason(((MajorCourseDBModel) getItem(position)).getRejectReason());
                                    CommonTipDialog.newInstance(rejectReason)
                                            .show(mActivity.getSupportFragmentManager(), "");
                                } catch (Exception e) {
                                }
                                break;
                            case R.id.copyBtn:
                                new CopyCourseAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.deleteBtn:
                                new DeleteCourseAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        uploadingCourseDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmmajor_course_uploading_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn: {
                                final int finalPosition = position;
                                new AlertDialog.Builder(mActivity)
                                        .setTitle(R.string.delete)
                                        .setMessage(R.string.are_you_sure_you_cancel_the_release_of_the_major_course)
                                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                try {
                                                    TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                                                        @Override
                                                        public Object call() throws Exception {
                                                            MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) getItem(finalPosition);
                                                            UploadFileDao.deleteByParentId(majorCourseDBModel.getId());
                                                            MajorCourseDBModelDao.deleteById(majorCourseDBModel.getId());
                                                            return null;
                                                        }
                                                    });
                                                } catch (SQLException e) {
                                                    Timber.e("onClick:" + Log.getStackTraceString(e));
                                                }
                                                remove(finalPosition);
                                            }
                                        })
                                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        })
                                        .create()
                                        .show();
                                break;
                            }
                        }
                    }
                }).build();
    }

    private void initLearnVideoDialog() {
        publishedLearnVideoDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_published_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.cancelPublishedBtn, R.id.editBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.cancelPublishedBtn:
                                new CancelPublishLearnVideoAsyncTask().execute(position);
                                break;
                            case R.id.editBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMAdapter.this);
                                } catch (Exception e) {

                                }
                                new EditLearnVideoAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "0");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteLearnVideoAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();

        notPublishedLearnVideoDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_not_published_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.publishedBtn, R.id.editBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.publishedBtn: {
                                new LearnVideoSubmitReviewAsyncTask().execute(position);
                                {
                                    Map<String, String> attrs = new HashMap<>();
                                    attrs.put("method", "0");
                                    trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD, TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD_LABEL, attrs);
                                }
                                break;
                            }
                            case R.id.editBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMAdapter.this);
                                } catch (Exception e) {

                                }
                                new EditLearnVideoAsyncTask(mActivity).execute(position);
                            {
                                Map<String, String> attrs = new HashMap<>();
                                attrs.put("method", "1");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD, TrackEvent.UNPUB_LEARN_VIDEO_PUB_METHOD_LABEL, attrs);
                            }
                            break;
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "1");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteLearnVideoAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        inReviewLearnVideoDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_inreview_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "2");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteLearnVideoAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        rejectLearnVideoDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_reject_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.editBtn, R.id.rejectReasonBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.editBtn:
                                currentPosition = position;
                                try {
                                    EventBus.getDefault().register(MMAdapter.this);
                                } catch (Exception e) {

                                }
                                new EditLearnVideoAsyncTask(mActivity).execute(position);
                                break;
                            case R.id.rejectReasonBtn:
                                String rejectReason = MomentUtil.extractRejectReason(((LearnVideoModel) getItem(position)).getRejectReason());
                                CommonTipDialog.newInstance(rejectReason)
                                        .show(mActivity.getSupportFragmentManager(), "");
                                break;
                            case R.id.deleteBtn:
                                HashMap<String, String> attrs = new HashMap<>();
                                attrs.put("status", "3");
                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                new DeleteLearnVideoAsyncTask().execute(position);
                                break;
                        }
                    }
                })
                .build();
        uploadingLearnVideoDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mmlearn_video_uploading_item_dialog)
                .viewIdList(R.id.cancelBtn, R.id.deleteBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteBtn: {
                                final int finalPosition = position;
                                new AlertDialog.Builder(mActivity)
                                        .setTitle(R.string.delete)
                                        .setMessage(R.string.are_you_sure_you_cancel_the_release_of_the_video)
                                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                try {
                                                    TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                                                        @Override
                                                        public Object call() throws Exception {
                                                            LearnVideoModel learnVideoModel = (LearnVideoModel) getItem(finalPosition);
                                                            UpdateBuilder<LearnVideoModel, String> updateBuilder = LearnVideoModelDao.getDao().updateBuilder();
                                                            updateBuilder.updateColumnValue(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                                                            updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                                                            updateBuilder.update();
                                                            List<UploadFile> uploadFileList = UploadFileDao.getDao().queryForEq(UploadFile.PARENT_ID_FIELD, learnVideoModel.getId());
                                                            for (UploadFile uploadFile : uploadFileList) {
                                                                UpdateBuilder<UploadFile, Integer> uploadFileUpdateBuilder = UploadFileDao.getDao().updateBuilder();
                                                                uploadFileUpdateBuilder.updateColumnValue(UploadFile.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE);
                                                                uploadFileUpdateBuilder.where().eq(UploadFile.ID_FIELD, uploadFile.getId());
                                                                uploadFileUpdateBuilder.update();
                                                            }
                                                            {
                                                                Map<String, String> attrs = new HashMap<>();
                                                                attrs.put("duration", String.valueOf(System.currentTimeMillis() - learnVideoModel.getReleaseDate()));
                                                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DEL_PUBLISHING_LEARN_VIDEO_DUR, TrackEvent.DEL_PUBLISHING_LEARN_VIDEO_DUR_LABEL, attrs);
                                                            }
                                                            {
                                                                HashMap<String, String> attrs = new HashMap<>();
                                                                attrs.put("status", "1");
                                                                trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.DELETE_LEARN_VIDEO_STATUS, TrackEvent.DELETE_LEARN_VIDEO_STATUS_LABEL, attrs);
                                                            }
                                                            return null;
                                                        }
                                                    });
                                                } catch (SQLException e) {
                                                    Timber.e("onClick:" + Log.getStackTraceString(e));
                                                }
                                                remove(finalPosition);
                                            }
                                        })
                                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        })
                                        .create()
                                        .show();
                                break;
                            }
                        }
                    }
                }).build();
    }


    public EventBus getEventBus() {
        return eventBus;
    }

    public void registerGlobalEventBus() {
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {

        }
    }

    public void unregisterGlobalEventBus() {
        try {
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {

        }
    }

    @Override
    public void onViewAttachedToWindow(BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        try {
            eventBus.register(holder);
        } catch (Exception e) {

        }
    }

    @Override
    public void onViewDetachedFromWindow(BaseViewHolder holder) {
        Timber.e("onViewDetachedFromWindow:");
        try {
            eventBus.unregister(holder);
        } catch (Exception e) {

        }
        super.onViewDetachedFromWindow(holder);
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder;
        switch (viewType) {
            case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                baseViewHolder = new LearnVideoViewHolder(getItemView(R.layout.mmlearn_video_item, parent));
                break;
            case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                baseViewHolder = new CourseViewHolder(getItemView(R.layout.mmmajor_course_item, parent));
                break;
            default:
                baseViewHolder = new BaseViewHolder(getItemView(R.layout.wild_card_item, parent));
                break;
        }
        return baseViewHolder;
    }

    @Override
    protected int getDefItemViewType(int position) {
        return getItem(position).getItemType();
    }

    @Override
    protected void convert(BaseViewHolder helper, MultiItemEntity item) {
        switch (item.getItemType()) {
            case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                ((LearnVideoViewHolder) helper).bindData((LearnVideoModel) item);
                break;
            case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                ((CourseViewHolder) helper).bindData((MajorCourseDBModel) item);
                break;
        }
    }

    public class LearnVideoViewHolder extends BaseViewHolder {
        LearnVideoModel model;
        @BindView(R.id.coverIv)
        RoundCornerImageView coverIv;
        @BindView(R.id.episodeTv)
        TextView episodeTv;
        @BindView(R.id.uploadStatusIv)
        ImageView uploadStatusIv;
        @BindView(R.id.uploadLayout)
        RelativeLayout uploadLayout;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.releaseDateTv)
        TextView releaseDateTv;
        @BindView(R.id.freeTv)
        TextView freeTv;
        @BindView(R.id.priceTv)
        TextView priceTv;
        @BindView(R.id.priceLayout)
        LinearLayout priceLayout;
        @BindView(R.id.moreBtn)
        ImageView moreBtn;
        @BindView(R.id.statusTv)
        TextView statusTv;
        @BindView(R.id.watchNumTv)
        TextView watchNumTv;
        @BindView(R.id.watchNumLayout)
        LinearLayout watchNumLayout;
        @BindView(R.id.likeIv)
        ImageView likeIv;
        @BindView(R.id.likeTv)
        TextView likeTv;
        @BindView(R.id.commentIv)
        ImageView commentIv;
        @BindView(R.id.commentTv)
        TextView commentTv;
        @BindView(R.id.collectionIv)
        ImageView collectionIv;
        @BindView(R.id.collectionTv)
        TextView collectionTv;
        @BindView(R.id.soldTv)
        TextView soldTv;
        @BindView(R.id.salesVolumeTv)
        TextView salesVolumeTv;
        @BindView(R.id.countLayout)
        LinearLayout countLayout;
        int currentUploadImgResId = 0;

        public LearnVideoViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        @OnClick({R.id.statusTv, R.id.moreBtn, R.id.uploadLayout})
        public void onViewClick(View view) {
            switch (view.getId()) {
                case R.id.statusTv: {
                    switch (model.getProgressStatus()) {
                        case PublishUtil.PROGRESS_STATUS_REJECT: {
                            try {
                                String rejectReason = MomentUtil.extractRejectReason(model.getRejectReason());
                                CommonTipDialog.newInstance(rejectReason)
                                        .show(mActivity.getSupportFragmentManager(), "");
                            } catch (Exception e) {
                            }
                            break;
                        }
                    }
                    break;
                }
                case R.id.uploadLayout: {
                    switch (model.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            UploadFileDao.resumeByParentId(model.getId());
                            LearnVideoModelDao.resumeById(model.getId());
                            bindData(model);
                            break;
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                            UploadFileDao.pauseByParentId(model.getId());
                            LearnVideoModelDao.pauseById(model.getId());
                            bindData(model);
                            break;
                    }
                    break;
                }
                case R.id.moreBtn: {
                    switch (model.getProgressStatus()) {
                        case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                        case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                        case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                        case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                        case PublishUtil.PROGRESS_STATUS_UPLOADING:
                        case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                        case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                            uploadingLearnVideoDialog.setPosition(getAdapterPosition());
                            uploadingLearnVideoDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                            notPublishedLearnVideoDialog.setPosition(getAdapterPosition());
                            notPublishedLearnVideoDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                        case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                            inReviewLearnVideoDialog.setPosition(getAdapterPosition());
                            inReviewLearnVideoDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                            publishedLearnVideoDialog.setPosition(getAdapterPosition());
                            publishedLearnVideoDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_REJECT:
                            rejectLearnVideoDialog.setPosition(getAdapterPosition());
                            rejectLearnVideoDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                    }
                    break;
                }
            }
        }

        public void bindData(LearnVideoModel data) {
            model = data;
            if (!TextUtils.isEmpty(data.getId())) {
                try {
                    LearnVideoModelDao.getDao().refresh(data);
                } catch (SQLException e) {
                    Timber.e("onEventPublishProgressStatusUpdate:" + Log.getStackTraceString(e));
                }
            }
            if (data.getControlOption() == PublishUtil.CONTROL_OPTION_DELETE) {
                remove(getAdapterPosition());
                return;
            }

            freeTv.setVisibility(View.INVISIBLE);
            priceLayout.setVisibility(View.VISIBLE);
            priceTv.setText(StringUtils.priceFormat(data.getPrice()));
            releaseDateTv.setText(DateFormatUtil.getStandardDate(data.getSellDate()));
            if (isEnableHighlight()) {
                titleTv.setText(Html.fromHtml(data.getTitle()));
            } else {
                titleTv.setText(data.getTitle());
            }
            soldTv.setText(StringUtils.formatNum(data.getSold()));
            salesVolumeTv.setText(StringUtils.priceFormat(data.getSalesVolume()));
            watchNumTv.setText(StringUtils.formatNum(data.getViewCount()));
            likeTv.setText(StringUtils.formatNum(data.getLikeCount()));
            collectionTv.setText(StringUtils.formatNum(data.getCollectCount()));
            commentTv.setText(StringUtils.formatNum(data.getCommentCount()));
            switch (data.getProgressStatus()) {
                case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                case PublishUtil.PROGRESS_STATUS_UPLOADING:
                case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                    switch (data.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                            if (currentUploadImgResId != R.drawable.upload) {
                                uploadStatusIv.setImageResource(R.drawable.upload);
                                currentUploadImgResId = R.drawable.upload;
                            }
                            break;
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            if (currentUploadImgResId != R.drawable.suspend) {
                                uploadStatusIv.setImageResource(R.drawable.suspend);
                                currentUploadImgResId = R.drawable.suspend;
                            }
                            break;
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                            if (currentUploadImgResId != R.drawable.suspend) {
                                uploadStatusIv.setImageResource(R.drawable.suspend);
                                currentUploadImgResId = R.drawable.suspend;
                            }
                            break;
                    }
                    uploadLayout.setVisibility(View.VISIBLE);
                    countLayout.setVisibility(View.GONE);
                    break;
                default:
                    uploadLayout.setVisibility(View.INVISIBLE);
                    countLayout.setVisibility(View.VISIBLE);
                    break;
            }

            switch (data.getProgressStatus()) {
                case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                case PublishUtil.PROGRESS_STATUS_UPLOADING:
                case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                    switch (data.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            statusTv.setText(R.string.not_published);
                            break;
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                            statusTv.setText(R.string.upload_failed_retry);
                            break;
                    }
                    break;
                case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    statusTv.setText(R.string.not_published);
                    break;
                case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    statusTv.setText(R.string.status_transcoding);
                    break;
                case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    statusTv.setText(R.string.in_review);
                    break;
                case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    statusTv.setText(R.string.published);
                    break;
                case PublishUtil.PROGRESS_STATUS_REJECT:
                    RxTextTool.getBuilder("")
                            .append(StringUtils.getString(R.string.reject)).setForegroundColor(ColorUtil.getColor(R.color.zwcolor_black_111111))
                            .append(StringUtils.getString(R.string.view_reason)).setForegroundColor(ColorUtil.getColor(R.color.zwcolor_red_fd5911))
                            .into(statusTv);
                    break;
            }
            GlideUtil.with(itemView.getContext())
                    .loadCover(data.getCoverUrl())
                    .into(coverIv);
            episodeTv.setText(String.format(itemView.getContext().getString(R.string.total_episode), data.getVideoNum()));
        }


        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onEventPublishProgressStatusUpdate(EventPublishProgressStatusUpdate event) {
            if (!TextUtils.isEmpty(model.getId())) {
                bindData(model);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventSelectGuarantee event) {
        switch (getItem(currentPosition).getItemType()) {
            case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                if (event.getResultCode() == EventSelectGuarantee.RESULT_OK) {
                    new CourseSubmitReviewAsyncTask().execute(currentPosition, event.getGuaranteeItemList());
                }
                break;
            case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                if (event.getResultCode() == EventSelectGuarantee.RESULT_OK) {
                    new LearnVideoSubmitReviewAsyncTask().execute(currentPosition, event.getGuaranteeItemList());
                }
                break;
        }
        unregisterGlobalEventBus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventSelectTraingCard event) {
        switch (getItem(currentPosition).getItemType()) {
            case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                if (event.getResultCode() == EventSelectTraingCard.RESULT_OK) {
                    new CourseBindTraingCardAsyncTask().execute(currentPosition, event.getTraingCardList());
                }
                break;
            case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                break;
        }
        unregisterGlobalEventBus();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventEditLearnVideoFinish(EventEditLearnVideoFinish event) {
        if (getItem(currentPosition).getItemType() == PublishUtil.PARENT_TYPE_LEARN_VIDEO) {
            if (event.getResultCode() == EventEditLearnVideoFinish.RESULT_OK) {
                try {
                    if (((LearnVideoModel) getItem(currentPosition)).getProgressStatus() == PublishUtil.PROGRESS_STATUS_PUBLISHED) {
                        trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.PUBLISH_LEARN_VIDEO_EDIT, TrackEvent.PUBLISH_LEARN_VIDEO_EDIT_LABEL);
                    }
                } catch (Exception e) {
                }
                setData(currentPosition, event.getLearnVideoModel());
                sortData();
                notifyDataSetChanged();
            }
        }
        unregisterGlobalEventBus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventEditMajorCourseFinish event) {
        if (getItem(currentPosition).getItemType() == PublishUtil.PARENT_TYPE_MAJOR_COURESE) {
            if (event.getResultCode() == EventEditMajorCourseFinish.RESULT_OK) {
                setData(currentPosition, event.getMajorCourseDBModel());
                sortData();
                notifyDataSetChanged();
            }
        }
        unregisterGlobalEventBus();
    }

    public void sortData() {
        Collections.sort(getData(), comparator);
    }


    public class CourseViewHolder extends BaseViewHolder {
        MajorCourseDBModel model;
        @BindView(R.id.coverIv)
        RoundCornerImageView coverIv;
        @BindView(R.id.locationIv)
        ImageView locationIv;
        @BindView(R.id.cityTv)
        TextView cityTv;
        @BindView(R.id.uploadStatusIv)
        ImageView uploadStatusIv;
        @BindView(R.id.uploadLayout)
        View uploadLayout;
        @BindView(R.id.coverLayout)
        FrameLayout coverLayout;
        @BindView(R.id.titleTv)
        TextView titleTv;
        @BindView(R.id.openClassDateTv)
        TextView openClassDateTv;
        @BindView(R.id.endClassDateTv)
        TextView endClassDateTv;
        @BindView(R.id.freeTv)
        TextView freeTv;
        @BindView(R.id.priceTv)
        TextView priceTv;
        @BindView(R.id.priceLayout)
        LinearLayout priceLayout;
        @BindView(R.id.priceContainer)
        FrameLayout priceContainer;
        @BindView(R.id.moreBtn)
        ImageView moreBtn;
        @BindView(R.id.statusTv)
        TextView statusTv;
        @BindView(R.id.watchNumTv)
        TextView watchNumTv;
        @BindView(R.id.watchNumLayout)
        LinearLayout watchNumLayout;
        @BindView(R.id.likeIv)
        ImageView likeIv;
        @BindView(R.id.likeTv)
        TextView likeTv;
        @BindView(R.id.commentIv)
        ImageView commentIv;
        @BindView(R.id.commentTv)
        TextView commentTv;
        @BindView(R.id.collectionIv)
        ImageView collectionIv;
        @BindView(R.id.collectionTv)
        TextView collectionTv;
        @BindView(R.id.soldTv)
        TextView soldTv;
        @BindView(R.id.salesVolumeTv)
        TextView salesVolumeTv;
        @BindView(R.id.countLayout)
        LinearLayout countLayout;
        @BindView(R.id.uploadPercentTv)
        TextView uploadPercentTv;
        int currentUploadImgResId = 0;

        public CourseViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        @OnClick({R.id.statusTv, R.id.moreBtn, R.id.uploadLayout})
        public void onViewClick(View view) {
            switch (view.getId()) {
                case R.id.statusTv: {
                    switch (model.getProgressStatus()) {
                        case PublishUtil.PROGRESS_STATUS_REJECT: {
                            try {
                                String rejectReason = MomentUtil.extractRejectReason(model.getRejectReason());
                                CommonTipDialog.newInstance(rejectReason)
                                        .show(mActivity.getSupportFragmentManager(), "");
                            } catch (Exception e) {
                            }
                            break;
                        }
                    }
                    break;
                }

                case R.id.uploadLayout: {
                    switch (model.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            UploadFileDao.resumeByParentId(model.getId());
                            MajorCourseDBModelDao.resumeById(model.getId());
                            bindData(model);
                            break;
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                            UploadFileDao.pauseByParentId(model.getId());
                            MajorCourseDBModelDao.pauseById(model.getId());
                            bindData(model);
                            break;
                    }
                    break;
                }
                case R.id.moreBtn: {
                    switch (model.getProgressStatus()) {
                        case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                        case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                        case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                        case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                        case PublishUtil.PROGRESS_STATUS_UPLOADING:
                        case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                        case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                        case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                            uploadingCourseDialog.setPosition(getAdapterPosition());
                            uploadingCourseDialog.show(mActivity.getSupportFragmentManager(), "");
                            break;
                        case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                            switch (model.getPublishSource()) {
                                case PublishUtil.PUBLISH_SOURCE_ANDROID:
                                case PublishUtil.PUBLISH_SOURCE_IOS:
                                    notPublishedCourseDialog.setPosition(getAdapterPosition());
                                    notPublishedCourseDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                                default:
                                    notPublishedCourseNoEditCopyDialog.setPosition(getAdapterPosition());
                                    notPublishedCourseNoEditCopyDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                            }
                            break;
                        case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                            switch (model.getPublishSource()) {
                                case PublishUtil.PUBLISH_SOURCE_ANDROID:
                                case PublishUtil.PUBLISH_SOURCE_IOS:
                                    serverTranscodingCourseDialog.setPosition(getAdapterPosition());
                                    serverTranscodingCourseDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                                default:
                                    serverTranscodingCourseNoEditCopyDialog.setPosition(getAdapterPosition());
                                    serverTranscodingCourseNoEditCopyDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                            }
                            break;
                        case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                            switch (model.getPublishSource()) {
                                case PublishUtil.PUBLISH_SOURCE_ANDROID:
                                case PublishUtil.PUBLISH_SOURCE_IOS:
                                    inReviewCourseDialog.setPosition(getAdapterPosition());
                                    inReviewCourseDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                                default:
                                    inReviewCourseNoEditCopyDialog.setPosition(getAdapterPosition());
                                    inReviewCourseNoEditCopyDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                            }
                            break;
                        case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                            switch (model.getPublishSource()) {
                                case PublishUtil.PUBLISH_SOURCE_ANDROID:
                                case PublishUtil.PUBLISH_SOURCE_IOS:
                                    publishedCourseDialog.setPosition(getAdapterPosition());
                                    publishedCourseDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                                default:
                                    publishedCourseNoEditCopyDialog.setPosition(getAdapterPosition());
                                    publishedCourseNoEditCopyDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                            }
                            break;
                        case PublishUtil.PROGRESS_STATUS_REJECT:
                            switch (model.getPublishSource()) {
                                case PublishUtil.PUBLISH_SOURCE_ANDROID:
                                case PublishUtil.PUBLISH_SOURCE_IOS:
                                    rejectCourseDialog.setPosition(getAdapterPosition());
                                    rejectCourseDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                                default:
                                    rejectCourseNoEditCopyDialog.setPosition(getAdapterPosition());
                                    rejectCourseNoEditCopyDialog.show(mActivity.getSupportFragmentManager(), "");
                                    break;
                            }
                            break;
                    }
                    break;
                }
            }
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onEvent(EventPublishProgressStatusUpdate event) {
            if (!TextUtils.isEmpty(model.getId())) {
                bindData(model);
            }
        }

        public void bindData(MajorCourseDBModel data) {
            model = data;
            if (!TextUtils.isEmpty(data.getId())) {
                try {
                    MajorCourseDBModelDao.getDao().refresh(data);
                    List<UploadFile> uploadFileList = UploadFileDao.getDao().queryForEq(UploadFile.PARENT_ID_FIELD, data.getId());
                    if (!ListUtil.isEmpty(uploadFileList)) {
                        long totalSize = 0;
                        long uploadedSize = 0;
                        for (UploadFile uploadFile : uploadFileList) {
                            totalSize += uploadFile.getTotalSize();
                            uploadedSize += uploadFile.getUploadedSize();
                        }
                        data.setUploadedPercent((float) uploadedSize * 100 / totalSize);
                    }
                } catch (Exception e) {
                    Timber.e("onEventPublishProgressStatusUpdate:" + Log.getStackTraceString(e));
                }
            }
            if (data.getControlOption() == PublishUtil.CONTROL_OPTION_DELETE) {
                remove(getAdapterPosition());
                return;
            }
            freeTv.setVisibility(View.INVISIBLE);
            priceLayout.setVisibility(View.VISIBLE);
            priceTv.setText(data.getPrice());
            try {
                ClassLocation classLocation = JSON.parseObject(data.getClassLocation(), ClassLocation.class);
                cityTv.setText(classLocation.getCity());
            } catch (Exception e) {
                cityTv.setText(R.string.unknown);
            }
            openClassDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", data.getStartClassDate()));
            endClassDateTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", data.getEndClassDate()));
            if (isEnableHighlight()) {
                titleTv.setText(Html.fromHtml(data.getTitle()));
            } else {
                titleTv.setText(data.getTitle());
            }
            soldTv.setText(StringUtils.formatNum(data.getSold()));
            salesVolumeTv.setText(StringUtils.priceFormat(data.getSalesVolume()));
            watchNumTv.setText(StringUtils.formatNum(data.getViewCount()));
            likeTv.setText(StringUtils.formatNum(data.getLikeCount()));
            collectionTv.setText(StringUtils.formatNum(data.getCollectCount()));
            commentTv.setText(StringUtils.formatNum(data.getCommentCount()));
            switch (data.getProgressStatus()) {
                case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                case PublishUtil.PROGRESS_STATUS_UPLOADING:
                case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                    switch (data.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                            if (currentUploadImgResId != R.drawable.upload) {
                                uploadStatusIv.setImageResource(R.drawable.upload);
                                currentUploadImgResId = R.drawable.upload;
                            }
                            break;
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            if (currentUploadImgResId != R.drawable.suspend) {
                                uploadStatusIv.setImageResource(R.drawable.suspend);
                                currentUploadImgResId = R.drawable.suspend;
                            }
                            break;
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                            if (currentUploadImgResId != R.drawable.suspend) {
                                uploadStatusIv.setImageResource(R.drawable.suspend);
                                currentUploadImgResId = R.drawable.suspend;
                            }
                            break;
                    }
                    countLayout.setVisibility(View.GONE);
                    uploadLayout.setVisibility(View.VISIBLE);
                    priceContainer.setVisibility(View.INVISIBLE);
                    uploadPercentTv.setVisibility(View.VISIBLE);
                    break;
                default:
                    countLayout.setVisibility(View.VISIBLE);
                    priceContainer.setVisibility(View.VISIBLE);
                    uploadPercentTv.setVisibility(View.INVISIBLE);
                    uploadLayout.setVisibility(View.INVISIBLE);
                    break;
            }
            uploadPercentTv.setText(String.valueOf((int) data.getUploadedPercent()) + "%");
            switch (data.getProgressStatus()) {
                case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                case PublishUtil.PROGRESS_STATUS_UPLOADING:
                case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                    switch (data.getControlOption()) {
                        case PublishUtil.CONTROL_OPTION_UPLOAD:
                        case PublishUtil.CONTROL_OPTION_PAUSE:
                            statusTv.setText(R.string.not_published);
                            break;
                        case PublishUtil.CONTROL_OPTION_FAILED_PAUSE:
                            statusTv.setText(R.string.upload_failed_retry);
                            break;
                    }
                    break;
                case PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED:
                    statusTv.setText(R.string.not_published);
                    break;
                case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                    statusTv.setText(R.string.status_transcoding);
                    break;
                case PublishUtil.PROGRESS_STATUS_IN_REVIEW:
                    statusTv.setText(R.string.in_review);
                    break;
                case PublishUtil.PROGRESS_STATUS_PUBLISHED:
                    statusTv.setText(R.string.published);
                    break;
                case PublishUtil.PROGRESS_STATUS_REJECT:
                    RxTextTool.getBuilder("")
                            .append(StringUtils.getString(R.string.reject)).setForegroundColor(ColorUtil.getColor(R.color.zwcolor_black_111111))
                            .append(StringUtils.getString(R.string.view_reason)).setForegroundColor(ColorUtil.getColor(R.color.zwcolor_red_fd5911))
                            .into(statusTv);
                    break;
            }
            GlideUtil.with(itemView.getContext())
                    .loadCover(data.getCoverUrl())
                    .into(coverIv);
        }
    }


    private class CancelPublishCourseAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... params) {
            position = (Integer) params[0];
            try {
                Moment moment = new Moment();
                moment.setId(((MajorCourseDBModel) getItem(position)).getGoodsId());
                Response<ResponseBody> response = ApiManager.getService().changeMomentStatus(moment.getId(), ActionEngine.GET_OFF, moment).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) getItem(position);
                    majorCourseDBModel.setProgressStatus(PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED);
                    setData(position, majorCourseDBModel);
                } catch (Exception e) {
                }
            }
        }
    }


    private class DeleteCourseAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;
        MajorCourseDBModel majorCourseDBModel = null;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... params) {
            position = (Integer) params[0];
            try {
                majorCourseDBModel = (MajorCourseDBModel) getItem(position);
                Response<ResponseBody> response = ApiManager.getService().deleteMoment(majorCourseDBModel.getGoodsId()).execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                remove(position);
                if (majorCourseDBModel != null) {
                    EventBus.getDefault().post(EventDeleteSearchMoment.newBuilder()
                            .serverId(majorCourseDBModel.getGoodsId())
                            .parentType(PublishUtil.PARENT_TYPE_MAJOR_COURESE)
                            .build());
                }
            }
        }
    }

    public class CourseBindTraingCardAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int position;
        List<TraingCard> traingCardList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            position = (int) objects[0];

            String goodsId = "";
            try {
                goodsId = ((MajorCourseDBModel) getItem(position)).getGoodsId();
            } catch (Exception e) {
                return e;
            }
            List list = (List) objects[1];
            List<CardBackup> cardBackupList = new LinkedList<>();
            for (Object item : list) {
                TraingCard traingCard = (TraingCard) item;
                traingCardList.add(traingCard);
                String cardType;
                switch (traingCard.getType()) {
                    case TraingCard.TYPE_COUNT_CARD:
                        cardType = Moment.TRAINING_CARD_TYPE_MEASURED_CARD;
                        break;
                    case TraingCard.TYPE_PREPAID_CARD:
                        cardType = Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD;
                        break;
                    case TraingCard.TYPE_TIME_CARD:
                        cardType = Moment.TRAINING_CARD_TYPE_TIME_CARD;
                        break;
                    default:
                        cardType = Moment.TRAINING_CARD_TYPE_TIME_CARD;
                        break;
                }
                CardBackup cardBackup = new CardBackup();
                cardBackup.setId(traingCard.getId());
                cardBackup.setTitle(traingCard.getTitle());
                cardBackup.setCardType(cardType);
                cardBackupList.add(cardBackup);
            }
            MajorCourse majorCourse = new MajorCourse();
            majorCourse.setBindCardBackup(cardBackupList);
            Moment moment = new Moment();
            moment.setMoreBackup(JSON.toJSONString(majorCourse));
            moment.setId(goodsId);
            moment.setSubject(Moment.SUBJECT_MAJOR_COURSE);
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .bindCardOrCourse(moment.getId(), ActionEngine.BIND_CARD_OR_COURSE, moment)
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    String json = JSON.toJSONString(traingCardList);
                    MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) getItem(position);
                    UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                    updateBuilder.updateColumnValue(MajorCourseDBModel.TRAING_CARD, json);
                    updateBuilder.where().eq(TraingClassDBModel.ID_FIELD, majorCourseDBModel.getId());
                    updateBuilder.update();
                    majorCourseDBModel.setTraingCard(json);
                    setData(position, majorCourseDBModel);
                } catch (Exception e) {
                    Timber.e("onPostExecute:" + Log.getStackTraceString(e));
                }
            }
        }
    }

    public class CourseSubmitReviewAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            position = (int) objects[0];
            String goodsId = "";
            try {
                goodsId = ((MajorCourseDBModel) getItem(position)).getGoodsId();
            } catch (Exception e) {
                return e;
            }
            Moment moment = new Moment();
            moment.setId(goodsId);
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .changeMomentStatus(moment.getId(), ActionEngine.PUT_ON, moment)
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) getItem(position);
                    try {
                        UpdateBuilder<MajorCourseDBModel, String> updateBuilder = MajorCourseDBModelDao.getDao().updateBuilder();
                        updateBuilder.updateColumnValue(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED);
                        updateBuilder.where().eq(MajorCourseDBModel.ID, majorCourseDBModel.getId());
                        updateBuilder.update();
                    } catch (Exception e) {
                    }
                    majorCourseDBModel.setProgressStatus(PublishUtil.PROGRESS_STATUS_PUBLISHED);
                    setData(position, majorCourseDBModel);
                } catch (Exception e) {
                    Timber.e("onPostExecute:" + Log.getStackTraceString(e));
                }
            }
        }
    }

    public class EditCourseAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;
        int editSourceType;
        Activity activity;

        public EditCourseAsyncTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                position = (Integer) objects[0];
                MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) getItem(position);
                String goodsId = majorCourseDBModel.getGoodsId();
                Response<ResponseBody> response = ApiManager.getService().getMoment(goodsId).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Moment moment = new Moment(JSON.parseObject(json, Moment.class));
                return MajorCourseFormModel.parse(moment, PublishUtil.OPERATION_TYPE_EDIT);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else if (o instanceof MajorCourseFormModel) {
                ARouter.getInstance()
                        .build(ARouterConfig.PublishMajorCourseFormPage)
                        .withParcelable("formModel", (Parcelable) o)
                        .navigation(activity, MMPage.REQUEST_CODE_PUBLISH);
            } else {
                ToastX.show(R.string.unknown_error);
            }
        }
    }

    public class CopyCourseAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;
        int editSourceType;
        Activity activity;

        public CopyCourseAsyncTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                position = (Integer) objects[0];
                MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) getItem(position);
                String goodsId = majorCourseDBModel.getGoodsId();
                Response<ResponseBody> response = ApiManager.getService().getMoment(goodsId).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Moment moment = new Moment(JSON.parseObject(json, Moment.class));
                return MajorCourseFormModel.parse(moment, PublishUtil.OPERATION_TYPE_COPY);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else if (o instanceof MajorCourseFormModel) {
                ARouter.getInstance()
                        .build(ARouterConfig.PublishMajorCourseFormPage)
                        .withParcelable("formModel", (Parcelable) o)
                        .navigation(activity, MMPage.REQUEST_CODE_PUBLISH);
            } else {
                ToastX.show(R.string.unknown_error);
            }
        }
    }


    public class LearnVideoSubmitReviewAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            position = (int) objects[0];
            String goodsId = "";
            try {
                goodsId = ((LearnVideoModel) getItem(position)).getGoodsId();
            } catch (Exception e) {
                return e;
            }
            Moment moment = new Moment();
            moment.setId(goodsId);
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .changeMomentStatus(moment.getId(), ActionEngine.PUT_ON, moment)
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    LearnVideoModel learnVideoModel = (LearnVideoModel) getItem(position);
                    UpdateBuilder<LearnVideoModel, String> updateBuilder = LearnVideoModelDao.getDao().updateBuilder();
                    updateBuilder.updateColumnValue(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED);
                    updateBuilder.where().eq(LearnVideoModel.ID_FIELD, learnVideoModel.getId());
                    updateBuilder.update();
                    learnVideoModel.setProgressStatus(PublishUtil.PROGRESS_STATUS_PUBLISHED);
                    setData(position, learnVideoModel);
                } catch (Exception e) {
                    Timber.e("onPostExecute:" + Log.getStackTraceString(e));
                }
            }
        }
    }

    public class EditLearnVideoAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;
        Activity activity;

        public EditLearnVideoAsyncTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                position = (Integer) objects[0];
                LearnVideoModel learnVideoModel = (LearnVideoModel) getItem(position);
                String goodsId = learnVideoModel.getGoodsId();
                String coverUrl = DownloadUtil.downloadCover(learnVideoModel.getCoverUrl());
                Response<ResponseBody> response = ApiManager.getService().getMoment(goodsId).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Moment moment = new Moment(JSON.parseObject(json, Moment.class));
                List<TagBackup> tagBackupList = moment.getTags();
                List<Interest> interestList = new LinkedList<>();
                List<Interest> industryList = new LinkedList<>();
                for (TagBackup tagBackup : tagBackupList) {
                    if (tagBackup == null || TextUtils.isEmpty(tagBackup.getId())) continue;
                    switch (tagBackup.getGroupType()) {
                        case SetupUtil.GROUP_TYPE_AVOCATION:
                            interestList.add(InterestUtil.convertTagBackupToInterest(tagBackup));
                            break;
                        case SetupUtil.GROUP_TYPE_CHANNEL:
                            industryList.add(InterestUtil.convertTagBackupToInterest(tagBackup));
                            break;
                    }
                }
                List<GuaranteeItem> guaranteeItemList = new LinkedList<>();
                List<Guarantee> guaranteeList = moment.getDetailBackup().getGuarantee();
                for (Guarantee guarantee : guaranteeList) {
                    guaranteeItemList.add(GuaranteeItem.newBuilder()
                            .id(guarantee.getId())
                            .title(guarantee.getName())
                            .content(guarantee.getDetail())
                            .build());
                }
                List<PublishLearnVideoItem> publishLearnVideoItemList = new LinkedList<>();
                VideoCourse videoCourse = JsonUtil.toObject(moment.getMoreBackup(), VideoCourse.class);
                List<SingleVideo> singleVideoList = videoCourse.getVideos();

                for (SingleVideo singleVideo : singleVideoList) {
                    publishLearnVideoItemList.add(PublishLearnVideoItem.newBuilder()
                            .preUpload(true)
                            .coverUrl(singleVideo.getCover())
                            .duration(singleVideo.getDuration())
                            .size(singleVideo.getSize())
                            .trail(singleVideo.getFree() == 1)
                            .videoUrl(singleVideo.getUrl())
                            .title(singleVideo.getTitle())
                            .build());
                }

                return PublishLearnVideoFormModel.newBuilder()
                        .operationType(PublishUtil.OPERATION_TYPE_EDIT)
                        .courseIntroduction(moment.getSummary())
                        .courseType(videoCourse.getCourseType())
                        .suitablePeople(videoCourse.getSuitablePopulation())
                        .learnTarget(videoCourse.getLearningGoals())
                        .coverUrl(coverUrl)
                        .goodsId(moment.getId())
                        .price(String.valueOf(moment.getCommodityBackup().getPrice()))
                        .platformDividend(videoCourse.getDivisionProportion() == null ? "" : StringUtils.priceFormatEscapeRedundantTailZero(videoCourse.getDivisionProportion() * 100))
                        .priceId(videoCourse.getApplePriceId())
                        .title(moment.getTitle())
                        .publishLearnVideoItemList(publishLearnVideoItemList)
                        .interestList(interestList)
                        .industryList(industryList)
                        .selectGuaranteeItemList(guaranteeItemList)
                        .teacher(videoCourse.getTeacher())
                        .build();
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else if (o instanceof PublishLearnVideoFormModel) {
                ARouter.getInstance()
                        .build(ARouterConfig.PublishLearnVideoPage)
                        .withParcelable("formModel", (Parcelable) o)
                        .navigation(activity, MMPage.REQUEST_CODE_PUBLISH);
            } else {
                ToastX.show(R.string.unknown_error);
            }
        }
    }


    private class CancelPublishLearnVideoAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... params) {
            position = (Integer) params[0];
            try {
                Moment moment = new Moment();
                moment.setId(((LearnVideoModel) getItem(position)).getGoodsId());
                Response<ResponseBody> response = ApiManager.getService().changeMomentStatus(moment.getId(), ActionEngine.GET_OFF, moment).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                try {
                    LearnVideoModel learnVideoModel = (LearnVideoModel) getItem(position);
                    learnVideoModel.setProgressStatus(PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED);
                    setData(position, learnVideoModel);
                } catch (Exception e) {
                }
            }
        }
    }


    private class DeleteLearnVideoAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        Integer position;
        LearnVideoModel learnVideoModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(mActivity)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... params) {
            position = (Integer) params[0];
            try {
                learnVideoModel = (LearnVideoModel) getItem(position);
                Response<ResponseBody> response = ApiManager.getService().deleteMoment(learnVideoModel.getGoodsId()).execute();
                if (response.code() != ResponseCode.NO_CONTENT) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                remove(position);
                if (learnVideoModel != null) {
                    EventBus.getDefault().post(EventDeleteSearchMoment.newBuilder()
                            .serverId(learnVideoModel.getGoodsId())
                            .parentType(PublishUtil.PARENT_TYPE_LEARN_VIDEO)
                            .build());
                }

            }
        }
    }
}
